import { Injectable } from '@angular/core';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Observable } from 'rxjs';

import { UserLockComponent } from '../components';
import { LoggerService, UserService } from '../services';

/**
 * 屏幕解锁验证守卫
 */
@Injectable({ providedIn: 'root' })
export class CanUnlockLeaveGuard implements CanDeactivate<UserLockComponent> {
    constructor(public msg: NzMessageService, private userSrv: UserService, public log: LoggerService) {}

    canDeactivate(
        component: UserLockComponent,
        currentRoute: ActivatedRouteSnapshot,
        currentState: RouterStateSnapshot,
        nextState?: RouterStateSnapshot
    ): boolean | Observable<boolean> | Promise<boolean> {
        return new Observable(observer => {
            this.log.logMsg('企图离开锁屏页面，正在验证解锁权限...', 'blue');
            const falg = this.userSrv.isLockScreen;
            if (falg) {
                this.msg.info('请输入正确登录密码，解锁屏幕...', { nzDuration: 2500 });
                observer.next(false);
                observer.complete();
            } else {
                observer.next(true);
                this.log.logMsg('屏幕解锁验证成功！！！', 'green');
                observer.complete();
            }
        });
    }
}
